<template>
	<div class="mb16">
		<button class="gjsx" @click="showClick">高级筛选 <img src="../img/高级筛选.png" style="height: 15px;" /></button>
		<div class="ml1">
			<el-input type="text" maxlength="20" placeholder="输入地址/房号/姓名" class="el-input" />
			<el-button type="primary" style="height: 40px; background-color: white;color: black; border: none;"
				@click="loadHouse">搜索</el-button>
		</div>
	</div>
	<div class="xiala" v-show="showXiala">
		<form>
			<el-form-item label="区域" class="xz">
				<el-cascader v-model="lastNumber.xz" :options="options" :props="props1" clearable />
			</el-form-item>
			<el-form-item label="使用状态" class="xz">
				<el-select v-model="form.usageStatus" placeholder="请选择使用状态">
					<el-option label="自主" value="自主" />
					<el-option label="闲置" value="闲置" />
					<el-option label="其他" value="其他" />
				</el-select>
			</el-form-item>
			<el-form-item label="产权人姓名" class="xz">
				<el-input v-model="form.owner" placeholder="请输入产权人姓名" clearable />
			</el-form-item>
			<el-form-item label="所在楼层" class="xz">
				<el-input v-model="form.floor" placeholder="请输入楼层" clearable />
			</el-form-item>
			<el-form-item label="房屋标签" class="xz">
				<el-select v-model="form.houseLabel" placeholder="请选择住户标签">
					<el-option v-for="item in data.biaoqian" :key="item.houseLabel" :label="item.houseLabel"
						:value="item.houseLabel"></el-option>
				</el-select>
			</el-form-item>
			<p style="width: 500px; height: 1px;">&nbsp;</p>
			<el-form-item label="销售状态" class="xz" style="width: 800px;">
				<el-select v-model="form.saleStatus" placeholder="请选择销售状态" style="width: 200px;right: 5px;">
					<el-option label="已销售" value="已销售" />
					<el-option label="未销售" value="未销售" />
				</el-select>
				<el-form-item>
					<el-col :span="11">
						<el-date-picker v-model="form.saleDate" type="month" value-format="YYYY-MM" placeholder="销售时间"
							style="width: 100%" />
					</el-col>
				</el-form-item>
			</el-form-item>
			<el-form-item label="收楼状态" class="xz" style="width: 800px;">
				<el-select v-model="form.handoverStatus" placeholder="请选择收楼状态" style="width: 200px;right: 5px;">
					<el-option label="已收楼" value="已收楼" />
					<el-option label="未收楼" value="未收楼" />
				</el-select>
				<el-form-item>
					<el-col :span="11">
						<el-date-picker v-model="form.handoverDate" value-format="YYYY-MM" type="month"
							placeholder="收楼时间" style="width: 100%" />
					</el-col>
				</el-form-item>
			</el-form-item>
			<el-form-item label="装修状态" class="xz" style="width: 800px;">
				<el-select v-model="form.renovationStatus" placeholder="请选择装修状态" style="width: 200px;right: 5px;">
					<el-option label="已装修" value="已装修" />
					<el-option label="未装修" value="未装修" />
				</el-select>
				<el-form-item>
					<el-col :span="11">
						<el-date-picker v-model="form.renovationDate" value-format="YYYY-MM" type="month"
							placeholder="装修时间" style="width: 100%" />
					</el-col>
				</el-form-item>
			</el-form-item>
			<el-form-item label="入住状态" class="xz" style="width: 800px;">
				<el-select v-model="form.occupancyStatus" placeholder="请选择入住状态" style="width: 200px;right: 5px;">
				</el-select>
				<el-form-item>
					<el-col :span="11">
						<el-date-picker v-model="form.occupancyDate" value-format="YYYY-MM" type="month"
							placeholder="入住状态" style="width: 100%" />
					</el-col>
				</el-form-item>
			</el-form-item>
			<div style="display: flex; width: 1000px;">
				<el-button class="btn1" @click="reset">重置</el-button><el-button class="btn2"
					@click="loadHouse">查询</el-button>
			</div>

		</form>
	</div>
	<div class="buttom">
		<div class="b_top">
			<el-button class="btn3" @click="AddHouse">新建房屋</el-button>
			<el-popover placement="bottom"  trigger="hover" class="el-popover">
				<template #reference>
					<el-button class="m-2">更多</el-button>
				</template>

				<div slot="content" style="margin: 0px; text-align: center;">
						<el-button @click="exportExcel" type="primary" class="button"
							style="width:70px;top:0;">导出</el-button>
				</div>
			</el-popover>
		</div>
		<el-table :data="data.house" style="width: 100% padding: 10px;">
			<el-table-column type="selection" width="55" />
			<el-table-column label="地址" width="200">
			  <template v-slot:default="scope">
			    {{ scope.row.regionName }}/ {{ scope.row.buildingName }}/{{scope.row.unitName}}/{{scope.row.floor}}/{{scope.row.houseNumber}}
			  </template>
			</el-table-column>
			<el-table-column prop="regionName" label="区域" width="100" />
			<el-table-column prop="buildingName" label="楼宇" width="60" />
			<el-table-column prop="unitName" label="单元" width="60" />
			<el-table-column prop="floor" label="楼层" width="60" />
			<el-table-column prop="houseNumber" label="房号" width="60" />
			<el-table-column prop="areaBuilding" label="建筑面积" width="80" />
			<el-table-column prop="areaInterior" label="套内面积" width="80" />
			<el-table-column prop="owner" label="产权人" width="120" />
			<el-table-column prop="usageStatus" label="房屋使用状态" width="120" />
			<el-table-column prop="houseLabel" label="房屋标签" width="120" />
			<el-table-column prop="saleStatus" label="销售状态" width="120" />
			<el-table-column prop="saleDate" label="销售日期" width="120" />
			<el-table-column prop="renovationStatus" label="装修状态" width="120" />
			<el-table-column prop="renovationDate" label="装修日期" width="120" />
			<el-table-column prop="occupancyStatus" label="入住状态" width="120" />
			<el-table-column prop="occupancyDate" label="入住日期" width="120" />
			<el-table-column fixed="right" label="操作" width="110">
				<template #default="{row}">
					<el-button link type="primary" @click="handleEdit(row)">
						修改
					</el-button>
					<el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="#626AEF" title="确定要删除吗"
						@confirm="handleDel(row.houseId)">
						<template #reference>
							<el-button link type="primary">删除</el-button>
						</template>
					</el-popconfirm>
				</template>
			</el-table-column>
		</el-table>
	</div>
	<div class="demo-pagination-block">
		<el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[5, 15, 25, 35]"
			:size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
			:total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
	</div>
</template>

<script lang="ts" setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue';
	import {
		ElTable
	} from 'element-plus';
	import type {
		ComponentSize
	} from 'element-plus';
	import {
		useRouter
	} from 'vue-router'
	import $http from '../router/AxiosApi';
import * as XLSX from "xlsx";
	
	// 定义响应式变量
	const showXiala = ref(false);
	const router = useRouter()

	// 定义函数来切换显示状态
	const showClick = () => {
		console.log("aaa");
		showXiala.value = !showXiala.value;
	};

	const AddHouse = () => {
		router.push({
			name: 'AddHouse'
		});
	}
	const data = reactive({
		house: [],
		houses: [],
		biaoqian: []
	})
	//表格数据
	const form = reactive({
		region: '',
		floor: '',
		saleStatus: '',
		saleDate: '',
		handoverStatus: '',
		handoverDate: '',
		renovationStatus: '',
		renovationDate: '',
		usageStatus: '',
		houseLabel: '',
		occupancyStatus: '',
		occupancyDate: '',
		owner: '',
		houseId: '',
		unitId: '',
		buildingId: '',
		regionId: '',
		billingItemsName: ''
	})

	//重置
	const reset = () => {
		for (let key in form) {
			form[key] = ''; // 将每个属性设置为空字符串
		}
		loadHouse()
	}
	const currentPage4 = ref(0)
	const pageSize4 = ref(0)
	const size = ref<ComponentSize>('default')
	const background = ref(false)
	const disabled = ref(false)
	const page = ref(1)
	const pageSize = ref(5)

	const total = ref(0)
	const handleSizeChange = (val : number) => {
		pageSize.value = val;
		loadHouse(page, pageSize);
	}
	const handleCurrentChange = (val : number) => {
		page.value = val;
		loadHouse(page, pageSize);
	}
	//查询全部信息
	onMounted(() => {
		loadHouse()
		loadAll()
		loadBiaoQian()
	})
	const loadHouse = () => {
		console.log(form)
		if (lastNumber.xz === undefined) {
			console.log("未选择");
			form.buildingId = ''
			form.houseId = ''
			form.regionId = ''
			form.unitId = ''
		} else {
			form.regionId = lastNumber.xz[0]; // 第一个选项作为 regionId
			if (lastNumber.xz.length >= 2) {
				form.buildingId = lastNumber.xz[1]; // 第二个选项作为 buildingId
			}
			if (lastNumber.xz.length >= 3) {
				form.unitId = lastNumber.xz[2]; // 第三个选项作为 unitId
			}
			if (lastNumber.xz.length >= 4) {
				form.houseId = lastNumber.xz[3]; // 第四个选项作为 houseId
			}
		}
		console.log(form)
		$http.post(`selectAll?currentPage=${page.value}&pageSize=${pageSize.value}`, form).then((res) => {
			data.house = res.data.data.list
			total.value = res.data.data.total
			currentPage4.value = res.data.data.pageNum
			pageSize4.value = res.data.data.pageSize
		})
			.catch((error) => {
				console.log("error:", error)
			})
	}

	const handleEdit = (row) => {
		// 将对象序列化成 JSON 字符串  
		const rowDataStr = JSON.stringify(row);
		router.push({
			path: '/updateHouse',
			query: {
				rowData: rowDataStr // 发送 JSON 字符串  
			}
		});
	};
	const props1 = {
		checkStrictly: true,
	}
	const options = reactive([]);
	const lastNumber = reactive({
		xz: ''
	})
	const loadAll = () => {
		$http.post("findAll").then((res) => {
			data.houses = res.data
			if (data.houses && data.houses.length > 0) {
				const regions = data.houses.map(houses => ({
					value: houses.regionId,
					label: houses.regionName,
					children: [
						{
							value: houses.buildingId,
							label: houses.buildingName,
							children: [
								{
									value: houses.unitId,
									label: houses.unitName,
									children: [
										{
											value: houses.houseId,
											label: houses.houseNumber
										}
									]
								}
							]
						}
					]
				}));

				// 更新 options 数组
				options.splice(0, options.length, ...regions);
			}
		})
	}


	const handleDel = (houseId) => {
		console.log(houseId)
		$http.delete(`delHouse?houseId=${houseId}`).then((res) => {
			console.log(res.data)
			loadHouse()
		})
	}
	const loadBiaoQian = () => {
		$http.post("findHouseBiaoQian").then((res) => {
			data.biaoqian = res.data
		})
	}

	//导出
	const exportExcel=()=>{
	  let tableData2 = [
	    ['地址', '区域', '楼宇', '单元', '房号', "建筑面积",'套内面积', '产权人', '房屋使用状态', "房屋标签","销售状态","销售日期","装修状态","装修日期","入住状态","入住日期"]//导出表头
	  ] // 表格表头
	  data.house.forEach((item, index) => {
	    let rowData = []
	    //导出内容的字段
	    rowData = [
	      item.regionName+"/"+item.buildingName+"/"+item.unitName+"/"+item.floor+"/"+item.houseNumber,
	      item.regionName,
		  item.buildingName,
	      item.unitName,
	      item.floor,
	      item.houseNumber,
	      item.areaBuilding,
	      item.areaInterior,
	      item.owner,
	      item.usageStatus,
		  item.saleStatus,
		  item.saleDate,
		  item.handoverStatus,
		  item.handoverDate,
		  item.renovationStatus,
		  item.renovationDate,
		  item.occupancyStatus,
		  item.occupancyDate,
		  item.houseLabel
	    ]
	    tableData2.push(rowData)
	  })
	  // 计算每列的最大宽度
	  const wscols = calculateColumnWidths(tableData2);
	
	  let workSheet = XLSX.utils.aoa_to_sheet(tableData2);
	  let bookNew = XLSX.utils.book_new();
	  // 设置自适应列宽度
	  workSheet['!cols'] = wscols;
	
	  XLSX.utils.book_append_sheet(bookNew, workSheet, '房屋数据') // 工作簿名称
	  let name = '房屋数据' + '.xlsx'
	  XLSX.writeFile(bookNew, name) // 保存的文件名
	}
	
	//设置列宽
	const calculateColumnWidths=(data)=>{
	  const wscols=[]
	
	  // 初始化列宽
	  for (let i = 0; i < data[0].length; i++) {
	    wscols.push({ wch: 10 }); // 初始宽度，可以根据实际需要设置
	  }
	
	  // 遍历数据，找出每列中最大的字符长度
	  for (let r = 0; r < data.length; r++) {
	    for (let c = 0; c < data[r].length; c++) {
	      const cellContent = data[r][c] !== null && data[r][c] !== undefined ? data[r][c].toString() : '';
	      const cellLength = getCellTextWidth(cellContent);
	
	      // 更新该列的最大宽度
	      if (!wscols[c] || cellLength > wscols[c].wch) {
	        wscols[c] = { wch: cellLength };
	      }
	    }
	  }
	
	  return wscols;
	}
	
	const  getCellTextWidth=(text)=>{
	  // 计算文本的宽度，可以根据需要调整计算方法
	  // 这里简单地使用字符串的长度作为宽度，可以根据实际情况优化
	  return text.length;
	}
</script>

<style scoped>
	.example-showcase .el-dropdown-link {
		cursor: pointer;
		color: var(--el-color-primary);
		display: flex;
		align-items: center;
	}

	.xiala {
		background-color: white;
		width: 98%;
		height: 50%;
		overflow: auto;
		padding: 15px;
		margin-bottom: 10px;
		border-radius: 10px;
	}

	.xz {
		width: 300px;
		float: left;
		margin-bottom: 0;
		margin-right: 32px;
		height: 56px;
		align-items: center;
		text-align: left;
	}

	.text-center {
		text-align: center;
	}

	.btn1 {
		position: relative;
		width: 100px;
		height: 40px;
		color: #7e8081;
		background-color: #fafafa;
		border: none;
		font-size: 14px;
		padding: 10px;
	}

	.btn2 {
		position: relative;
		width: 100px;
		height: 40px;
		color: #fff;
		background-color: #00c36d;
		border-color: #00c36d;
		font-size: 14px;
	}

	.gjsx {
		background-color: white;
		padding: 10px 15px;
	}

	.mb16 {
		margin-bottom: 16px;
		display: -webkit-box;
		display: flex;
		justify-content: flex-end;
		width: 100%;
	}

	.ml1 {
		width: 300px;
		border: none;
		margin-left: 10px;
		display: inline-table;
	}

	.el-input {
		width: 240px;
		height: 40px;
		line-height: 40px;
		border: none;
	}

	.u1 {
		margin: 0px;
		padding: 0px;
	}

	.u1>li {
		list-style: none;
		line-height: 20px;
		height: 25px;
		line-height: 190%;
		text-align: left;
		padding: 5px 10px;
		cursor: pointer;
	}

	.u1>li:hover {
		background-color: #d3ffe2;
		/* 鼠标悬浮时的背景色 */
		color: #00bd00;
	}

	.el-popover {
	}

	.buttom {
		background-color: white;
		padding: 10px;
		border-radius: 10px;
	}

	.btn3 {
		width: 100px;
		height: 40px;
		color: #fff;
		background-color: #00c36d;
		border-color: #00c36d;
		font-size: 14px;
		margin-bottom: 10px;
	}

	.b_top {
		display: flex;
		justify-content: space-between;
	}

	.m-2 {
		padding: 10px 20px;
		align-items: center;
		background-color: #fafafa;
		border: none;
		height: 40px;
		width: 80px;

	}
</style>